import logging
if __name__ == "__main__":
    # 导入 Django 的环境
    import django
    import sys
    import os

    # 导入django项目的根目录，可以随意导入模块
    django_root_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
    sys.path.insert(0, django_root_path)

    ##导入django环境，能够直接使用django的orm和cache等对象
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tinyurl.settings")
    django.setup()

from django.conf import settings
import os
from datetime import datetime
class TotalLogger:
    def __init__(self, level='info', redirect=None):
        '''
        Args:
            level: 日志等级,info,warning,error,fatal,critical
            redirect: 日志文件存放的目录,一般字符串
            其上级目录是：项目根目录下/log
        '''
        self.level = level
        self.redirect = redirect
        leve_list = ['notset', 'info', 'debug', 'warn', 'warning', 'error', 'fatal', 'critical']
        if self.level not in leve_list:
            raise Exception(f'日志等级不能是: {level}')

    def save_log(self, msg: str):
        '''
        Args:
            msg: 日志的内容
        Return:
            None
        '''
        ## 对于minio的操作，日志记录到log/minio
        if self.redirect:
            dir_path = os.path.join(settings.BASE_DIR, 'log', self.redirect)
        else:
            dir_path = os.path.join(settings.BASE_DIR, 'log')
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)
        ## 日志文件路径
        log_file_path = os.path.join(dir_path, f'{datetime.now().strftime("%Y-%m-%d")}-{self.level}.log')

        # 定义一个logging的对象，命名为service_info
        LOGGER = logging.getLogger(log_file_path)

        # 设置级别
        if self.level == 'notset':
            LOGGER.setLevel(logging.NOTSET)
        if self.level == 'debug':
            LOGGER.setLevel(logging.DEBUG)
        elif self.level == 'info':
            LOGGER.setLevel(logging.INFO)
        elif self.level in ['warning', 'warn']:
            LOGGER.setLevel(logging.WARNING)
        elif self.level == 'error':
            LOGGER.setLevel(logging.ERROR)
        elif self.level == 'fatal':
            LOGGER.setLevel(logging.ERROR)
        elif self.level == 'critical':
            LOGGER.setLevel(logging.CRITICAL)
        else:
            LOGGER.setLevel(logging.INFO)

        if not LOGGER.handlers:
            # 创建一个handler，用于写入日志文件
            fh = logging.FileHandler(log_file_path, encoding='utf-8')
        else:
            fh = LOGGER.handlers[0]
        fh.setLevel(logging.INFO)
        # 定义handler的输出格式
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                                      datefmt='%Y-%m-%d %H:%M:%S')
        fh.setFormatter(formatter)
        # 给Logger添加handler
        LOGGER.addHandler(fh)
        # 在控制台显示
        LOGGER.propagate = True
        LOGGER.__getattribute__(self.level)(msg)
        # LOGGER.__getattribute__(level)('##################分割行###################')
        fh.close()

__logger = TotalLogger(redirect='short_url')
logger = __logger.save_log
if __name__ == '__main__':
    logger('xxxx')